<template>
  <div class="chat-container">
    <div class="chat-history">
      <el-card class="message" v-for="message in messages" :key="message.id">
        <div
          class="message-content"
          :class="{ 'user-message': message.role === 'user', 'bot-message': message.role === 'bot' }"
        >
          <div v-if="message.role === 'user'" class="message-role">You:</div>
          <div v-else class="message-role">Bot:</div>
          <div class="message-text">
            <template v-if="message.typing">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </template>
            <template v-else-if="message.typewriter">
              <span>{{ message.typewriterText }}</span>
            </template>
            <template v-else>{{ message.content }}</template>
          </div>
        </div>
      </el-card>
      <div class="bottom-anchor" ref="bottomAnchor"></div>
    </div>
    <div class="chat-input">
      <el-input v-model="inputText" placeholder="Type your message..." @keyup.enter="sendMessage"></el-input>
      <el-button type="primary" @click="sendMessage">Send</el-button>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "Chat",
  data() {
    return {
      messages: [], // 存储聊天消息的数组
      inputText: "" // 输入框文本
    };
  },
  mounted() {
    this.scrollToBottom();
  },
  methods: {
    // 发送用户消息
    sendMessage() {
      const userMessage = {
        id: new Date().getTime(),
        role: "user",
        content: this.inputText
      };
      this.messages.push(userMessage);
      this.inputText = "";

      // 添加正在输入中的提示
      this.messages.push({
        id: new Date().getTime(),
        role: "bot",
        content: "",
        typing: true
      });

      // 调用后端API发送用户消息并获取机器人回答
      this.getBotReply(userMessage.content);
    },
    // 调用后端API获取机器人回答
    getBotReply(question) {
      // 发送请求到后端API，将问题发送给后端
      // 在这里使用axios或fetch等HTTP请求库
      // 接收后端返回的回答，并将回答添加到this.messages数组中

      // 示例代码：
      axios
        .post("/chat", { question: question })
        .then(response => {
          // 移除正在输入中的提示
          this.messages.pop();

          // 添加回答的打字机效果
          const botReply = {
            id: new Date().getTime(),
            role: "bot",
            content: response.data.reply,
            typewriter: true,
            typewriterText: ""
          };
          this.messages.push(botReply);
          this.typewriterEffect(botReply);

          this.scrollToBottom();
        })
        .catch(error => {
          console.error("Error:", error);
        });
    },
    typewriterEffect(message) {
      const text = message.content;
      let index = 0;

      const typingInterval = setInterval(() => {
        message.typewriterText += text[index];
        index++;

        if (index >= text.length) {
          clearInterval(typingInterval);
          message.typewriter = false;
        }
      }, 100);
    },
    scrollToBottom() {
      this.$nextTick(() => {
        this.$refs.bottomAnchor.scrollIntoView({ behavior: "smooth" });
      });
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 80vh;
  border: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box;
}

.chat-history {
  flex: 1;
  overflow-y: scroll;
}

.message {
  margin-bottom: 10px;
}

.message-content {
  padding: 5px;
  border-radius: 5px;
}

.user-message {
  background-color: #f0f0f0;
}

.bot-message {
  background-color: #e0e0e0;
}

.message-role {
  font-weight: bold;
}

.message-text {
  margin-top: 5px;
}

.typing-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
}

.typing-indicator span {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin-right: 4px;
  border-radius: 50%;
  background-color: #bbb;
  animation: typing-indicator 1s infinite;
}

@keyframes typing-indicator {
  0% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.5;
  }
}

.chat-input {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.el-input {
  flex: 1;
  margin-right: 10px;
}

.el-button {
  margin-left: 10px;
}

.bottom-anchor {
  visibility: hidden;
}
</style>
